package cn.edu.yzu.scholarship.controller;


import java.io.File;
import java.util.List;
import java.util.Map;

import cn.edu.yzu.scholarship.constant.C;
import cn.edu.yzu.scholarship.kit.Sak;
import cn.edu.yzu.scholarship.model.Grant;
import cn.edu.yzu.scholarship.render.FileExtendRender;

import com.jfinal.core.Controller;
import com.jfinal.ext.plugin.sqlinxml.SqlKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class GrantCtrler extends Controller {
	
	public void years() {
		renderJson(Grant.getYears());
	}
	
	public void classify() {
		renderJson(Grant.getClassifys());
	}

	public void list() {
		Map<String,String> params = Sak.newHashMap();
		params.put("startdate", getPara("startdate", "-"));
		params.put("enddate", getPara("enddate", "-"));
		params.put("xh", getPara("xh", "-"));
		params.put("lqyxsm", getPara("lqyxsm", "-"));
		params.put("scholarshipId", getPara("scholarshipId", "-"));
		
		if(C.UT_STUDENT == (Integer)getSessionAttr("userType")) {//学生只能查看自己的信息
			params.put("xh", ((Record)getSessionAttr("user")).getStr("xh"));
		}
		
		renderJson(Grant.paginate(getParaToInt("page"), getParaToInt("rows"), params));
	}
	
	public void fusionChartData() {
		String sql = "grant.groupMoneyByMonth";
		if("college".equals(this.getPara("type"))) {
			sql = "grant.groupMoneyByCollege";
		} else if ("scholar".equals(this.getPara("type"))) {
			sql = "grant.groupMoneyByScholar";
		}
		
		renderJson(Db.find(SqlKit.sql(sql)));
	}
	
	public void files() {
		renderJson(Grant.paginateFiles(getParaToInt("page"), getParaToInt("rows")));
	}
	
	public void download() {
		Record record = Db.findById("grant", getPara("id"));
		render(new FileExtendRender(record.getStr("title"), new File(C.GRANT_FOLDER + record.getStr("path"))));
		//renderFile(new File(C.GRANT_FOLDER + getPara("file")));
	}
	
	public void revocation() {
		List<Record> sids = Db.find("select scholarshipId from grantDetail where grantId = ?",getPara("id"));
		for(Record sid : sids) {
			Db.update("update scholarship set lastGrant = (select max(grantTime) from grantDetail where grantId = ?) where id = ?", getPara("id"), sid.get("scholarshipId"));
		}
		
		Db.deleteById("grant", getPara("id"));
		Db.deleteById("grantDetail", "grantId", getPara("id"));
		
		renderJson("errorInfo","none");
	}
}
